//
//  FZH_ScrollView.swift
//  FirstSwiftProduct
//
//  Created by 知合金服-Mini on 2017/10/26.
//  Copyright © 2017年 范泽华. All rights reserved.
//

import UIKit

protocol imageViewTapDelegate:class {
    func tapIndex(index:Int)
}

class FZH_ScrollView: UIView ,UIScrollViewDelegate{

    weak var delegate : imageViewTapDelegate?
    
    
    var _imageArr : Array<AnyObject>!
    
    //图片数组
    var imageArr: Array<AnyObject>? {
        get {
           
            return _imageArr
        }
        set {
            
            _imageArr = newValue
            if _imageArr?.count == 1 {
                _imageArr = [_imageArr![0],_imageArr![0],_imageArr![0]]
                self.pageControl.numberOfPages = 0
                self .changeImage(left: _imageArr.count-1 , mid: 0, right: 1)
            }else{
                self.pageControl.numberOfPages = (_imageArr?.count)!
                self .changeImage(left: _imageArr.count-1 , mid: 0, right: 1)
            }
            self.addTime()
        }
    }
    //自动滚动间隔
//    var _autoScrollDeley : TimeInterval
    
    var autoScrollDeley: TimeInterval! = TimeInterval()
        
    
    
    //自动轮播
    var _isScroll : Bool = Bool()
    
    var isScroll: Bool {
        get {
            return _isScroll
        }
        set {
            _isScroll = newValue
            if _isScroll && _imageArr.count > 1 {
                self.autoScrollDeley = 3;
            }
        }
    }
    
    //私有
    
    //滚动左边的图
    private  var leftImageView :UIImageView!
    //滚动右边
    private var rightImageView :UIImageView!
//    滚动中间
    private var midImageView : UIImageView!
//    现在的Index
    private var currentIndex :NSInteger!
    
    //page控件
    private var pageControl :UIPageControl!
    //滚动试图
    private var scrollImageView :UIScrollView!
    //size
    private var scorllViewSize :CGSize!
    //定时器
    private var timer :Timer!
    
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        fatalError("init(coder:) has not been implemented")
        
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
//        self.pageControl = UIPageControl.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
       self.scorllViewSize = self.frame.size
        self.loadImages()
        
        let tagest = UITapGestureRecognizer.init(target: self, action: #selector(tapAction))
        self.midImageView.isUserInteractionEnabled = true
        self.midImageView.addGestureRecognizer(tagest)
    }
    
    
    func tapAction() -> Void {
//        print(currentIndex)
        delegate?.tapIndex(index: currentIndex)
    }
    
    func loadImages() -> Void {
        
        self.currentIndex = 0
        // 初始化scrollImageView
        self.scrollImageView = UIScrollView.init(frame: CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height))
        self.scrollImageView.backgroundColor = UIColor.gray
        self.scrollImageView.isPagingEnabled = true
        self.scrollImageView.showsHorizontalScrollIndicator = false
        self.scrollImageView.delegate = self
        self.scrollImageView.contentSize = CGSize(width: self.scorllViewSize.width * 3, height: 0)
        self.addSubview(self.scrollImageView)
        
        ////重用的imageView
        self.leftImageView = UIImageView.init(frame: CGRect(x: 0, y: 0, width: self.scorllViewSize.width, height: self.scorllViewSize.height))
        self.midImageView = UIImageView.init(frame: CGRect(x: self.scorllViewSize.width, y: 0, width: self.scorllViewSize.width, height: self.scorllViewSize.height))
        
        self.rightImageView = UIImageView.init(frame: CGRect(x: self.scorllViewSize.width * 2, y: 0, width: self.scorllViewSize.width, height: self.scorllViewSize.height))
        
        self.scrollImageView.addSubview(self.leftImageView)
        self.scrollImageView.addSubview(self.rightImageView)
        self.scrollImageView.addSubview(self.midImageView)
        //分页控制 UIPageControl初始化
        self.pageControl = UIPageControl.init(frame: CGRect(x: 0, y: self.scorllViewSize.height - 16, width: self.scorllViewSize.width, height: 16))
        //默认颜色
        self.pageControl.pageIndicatorTintColor = UIColor.white
//        当前颜色
        self.pageControl.currentPageIndicatorTintColor = UIColor.gray
        self.pageControl.currentPage = self.currentIndex
        self.addSubview(self.pageControl)
        
        
    }
    
    func addTime() -> Void {
        if self.timer == nil {
            self.timer = Timer.init(timeInterval: 3.0, target: self, selector: #selector(scrollScroll), userInfo: nil, repeats: true)
            RunLoop.main.add(self.timer, forMode: RunLoopMode.commonModes)
        }
        
    }
    
     func scrollScroll() -> Void {
        
        self.scrollImageView.setContentOffset(CGPoint.init(x: self.scrollImageView.contentOffset.x + self.scorllViewSize.width, y: 0), animated: true)
    }
    
    
    private func changeImage(left:NSInteger,mid:NSInteger,right:NSInteger)->Void{
        //给重用的三个imageView附上图片
        self.leftImageView.sd_setImage(with:URL.init(string: self.imageArr![left] as! String), placeholderImage: UIImage.init(named: " "), options: .retryFailed) { (image, error, cacheType, url) in
           
        }
        
        self.rightImageView.sd_setImage(with:URL.init(string: self.imageArr![right] as! String), placeholderImage: UIImage.init(named: " "), options: .retryFailed) { (image, error, cacheType, url) in
           
        }
        self.midImageView.sd_setImage(with:URL.init(string: self.imageArr![mid] as! String), placeholderImage: UIImage.init(named: " "), options: .retryFailed) { (image, error, cacheType, url) in
           
        }
//        self.leftImageView.image = self.imageArr![left]
//        self.rightImageView.image = self.imageArr![right]
//        self.midImageView.image = self.imageArr![mid]
        //显示在屏幕的其实是第二张图片
        self.scrollImageView.setContentOffset(CGPoint.init(x: self.scorllViewSize.width, y: 0), animated: false)
    }
    
    
    public func removeTimer(){
        if self.timer != nil {
            self.timer.invalidate()
            self.timer = nil;
        }
        
    }
    
    
    //UIScrollViewDelegate
    // 开始用手滚动时干掉定时器
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.removeTimer()
    }
    // 用手滚动结束时重新添加定时器
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        self.addTime()
    }
    //滚动时计算scrollView
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offSetX = self.scrollImageView.contentOffset.x
        
        if self.imageArr?.count == 1 {
            self.changeImage(left: 0, mid: 0, right: 0)
        }
        
        //右滑
       //  = pageControl.currentPage变换才会流畅

        if offSetX >= self.scrollImageView.frame.size.width * 2 {
            self.currentIndex = self.currentIndex + 1
            if self.currentIndex == self.imageArr?.count{
                self.currentIndex = 0
                self.changeImage(left: (self.imageArr?.count)! - 1, mid: 0, right: 1)
            }else if self.currentIndex == (self.imageArr?.count)! - 1{
                self.changeImage(left: self.currentIndex - 1, mid: (self.imageArr?.count)! - 1, right: 0)
            }else{
                self.changeImage(left: self.currentIndex - 1, mid: self.currentIndex, right: self.currentIndex + 1)
            }
            
        }
        //    左滑
        if offSetX <= 0 {
            self.currentIndex = self.currentIndex - 1
            if self.currentIndex == -1{
                self.currentIndex = (self.imageArr?.count)! - 1
                self .changeImage(left: self.currentIndex - 1, mid: self.currentIndex, right: 0)
            }else if self.currentIndex == 0{
                self .changeImage(left: (self.imageArr?.count)! - 1, mid: self.currentIndex, right: self.currentIndex + 1)
            }else{
                self.changeImage(left: self.currentIndex - 1, mid: self.currentIndex, right: self.currentIndex+1)
            }
            
            
        }
        self.pageControl.currentPage = currentIndex
//        print(currentIndex)
        
    }
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
